import { language } from './language';

// 语言类型
export type Language = 'zh-CN' | 'en-US';

// 语言索引
export enum LanguageIndex {
  ZH_CN = 0,
  EN_US = 1
}

// 类型定义
interface LanguageStructure {
  [section: string]: {
    [key: string]: string[] | {
      [subKey: string]: string[];
    };
  };
}

// 获取语言索引
export const getLanguageIndex = (lang: Language): LanguageIndex => {
  return lang === 'zh-CN' ? LanguageIndex.ZH_CN : LanguageIndex.EN_US;
};

/**
 * 根据键和语言获取翻译文本
 * @param key 键，格式为 'section.key' 或 'section.subsection.key'
 * @param lang 语言
 * @returns 翻译文本，如果找不到则返回键本身
 */
export const t = (key: string, lang: Language = 'zh-CN'): string => {
  try {
    const langIndex = getLanguageIndex(lang);
    const keys = key.split('.');
    
    // 简单路径
    if (keys.length === 2) {
      const [section, subKey] = keys;
      const langSection = (language as LanguageStructure)[section];
      if (langSection && Array.isArray(langSection[subKey])) {
        return (langSection[subKey] as string[])[langIndex];
      }
    }
    // 嵌套路径
    else if (keys.length === 3) {
      const [section, subSection, subKey] = keys;
      const langSection = (language as LanguageStructure)[section];
      if (langSection && typeof langSection[subSection] === 'object' && !Array.isArray(langSection[subSection])) {
        const subSectionObj = langSection[subSection] as { [key: string]: string[] };
        if (subSectionObj[subKey]) {
          return subSectionObj[subKey][langIndex];
        }
      }
    }
    
    // 找不到翻译，返回原始键
    return key;
  } catch (error) {
    console.error(`翻译错误 - 键: ${key}, 语言: ${lang}`, error);
    return key;
  }
};

// 重新导出，保持与原有代码兼容
export { language };
